Skip to content

Allow initializing NonZero with literals #143594

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

oli-obk
Copy link
Contributor

@oli-obk oli-obk commented Jul 7, 2025

This basically implements rust-lang/rfcs#3786 by teaching the language about NonZero and the literals NonZero supports.

I believe it is a minor enough feature that it either doesn't need an RFC and can just be FCPed or it is a simple enough RFC that @rust-lang/lang could FCP it to set a precedent for doing this for other libcore types. Anything like this for user types would of course require a full RFC as there are many open questions around it that NonZero<T> just doesn't have.

@oli-obk oli-obk added T-lang Relevant to the language team needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. labels Jul 7, 2025
@traviscross
Copy link
Contributor

We'll also need to update the Reference for this, and the details in that PR would help form another basis for the FCP here.

cc @ehuss

@traviscross traviscross added the S-waiting-on-documentation Status: Waiting on approved PRs to documentation before merging label Jul 7, 2025

fn main() {
let _: std::num::NonZero<u8> = 256;
//~^ ERROR literal out of range
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's the erroring example

@oli-obk oli-obk force-pushed the non-zero-literals branch from cf76d4e to 8797188 Compare July 8, 2025 06:40
@oli-obk oli-obk force-pushed the non-zero-literals branch from 8797188 to 94dadf4 Compare July 8, 2025 07:34
rust-bors bot added a commit that referenced this pull request Jul 8, 2025
Limited nonzero coercion

coercing `NonZero<T>` to `T` if all the types are available at the cast site.

This is fairly limited, as (as the tests show), this does not allow "reborrowing" `&NonZero<T>` as `&T`. It also fails quickly if the types aren't fully clear at the coercion site, but only resolved later.

Also cannot aid in trait selection or similar, even if there is clearly only one option.

Related:

* #143594
* rust-lang/rfcs#3786

cc `@traviscross`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. S-waiting-on-documentation Status: Waiting on approved PRs to documentation before merging T-lang Relevant to the language team
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants